package com.ysq.excavator.service.impl;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.search.Query;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.ysq.excavator.config.ConfigInfo;
import com.ysq.excavator.entity.LuceneField;
import com.ysq.excavator.entity.QueryAttribute;
import com.ysq.excavator.entity.TreeNode;
import com.ysq.excavator.lucene.LuceneManager;
import com.ysq.excavator.service.LuceneService;
import com.ysq.excavator.util.CommonUtil;

/**
 * lucene 管理类
 * @author Administrator
 *
 */
@Service("luceneServiceImpl")
public class LuceneServiceImpl implements LuceneService {

	/**
	 * 分页查找所有 documents
	 * @param start
	 * @param indexPath
	 * @return
	 */
	public String findAllDocuments(QueryAttribute queryAttr,int limit,int start,String indexPath){
		
		StringBuilder builder = new StringBuilder();
		builder.append("{");
		//{"total":100,"rows":[{"attr1":"attr14","itemid":"ItemId4","listprice":4,"productid":"productid4","status":"status4","unitcost":4}]}"
		List<Map<String, Object>> mapList = null;
		LuceneManager manager = null;
		try {
			manager = new LuceneManager(indexPath);
			
			Query query = manager.getQuery(queryAttr);
			
			mapList = manager.luceneStrongQuery(query,start, limit);
			
			String rowsJson = JSON.toJSONString(mapList);
			
			String columnsJson = CommonUtil.getColumnJson(manager.fieldSet);
			
			builder.append("\"total\":" + manager.totalResult);
			
			builder.append(",\"rows\":" + rowsJson);
			
			builder.append(",\"columns\":[" + columnsJson + "]");
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		builder.append("}");
		return builder.toString();
	}
	
	/**
	 * 获得 lucene 索引目录树
	 * @return
	 */
	public String getLuceneTreeJson(){
		List<TreeNode> nodeList = new ArrayList<TreeNode>();

		File indexFolder = new File(ConfigInfo.LUCENE_INDEX_PATH);
		File[] childFiles = indexFolder.listFiles();
		
		for(File file : childFiles){
			String path = file.getPath();
			TreeNode child = new TreeNode();
			
			child.setId(path);
			child.setText(path);
			child.setState(false);
			nodeList.add(child);
		}
		String jsonResult = JSON.toJSONString(nodeList);
		
		return jsonResult;
	}
	
	/**
	 * 根据 id 删除lucene index
	 * @param contentidList
	 */
	public String deleteIndexById(String indexPath,List<Long> contentidList){
		LuceneManager manager = null;
		boolean flag = false;
		
		try {
			manager = new LuceneManager(indexPath);
			
			flag = manager.deleteDocuments(contentidList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String result = CommonUtil.returnAjaxJson(flag, "删除失败");
		
		if(flag){
			result = CommonUtil.returnAjaxJson(flag, "删除成功");
		}
		return result;
	}
	
	/**
	 * 插入一条新数据
	 * @param indexPath
	 * @param docFieldList
	 */
	public String insertOneDocument(String indexPath,List<LuceneField> docFieldList){
		String resultJson = "";
		Map<String, LuceneField> fieldMap = new HashMap<String, LuceneField>();
		for(LuceneField luceneField : docFieldList){
			fieldMap.put(luceneField.getFieldName(), luceneField);
		}
		
		if(fieldMap.containsKey("contentid")){
			
			Document doc = LuceneField.createDocument(fieldMap);
			
			if(doc == null){
				resultJson = CommonUtil.returnAjaxJson(false, "数据有误！");
				return resultJson;
			}else{
				//先查找是否包含contentid
				String contentid = fieldMap.get("contentid").getFieldValue();
				
				try {
					LuceneManager manager = new LuceneManager(indexPath);
					
					int count = manager.getContentCount(contentid);
					if(count > 0){
						resultJson = CommonUtil.returnAjaxJson(false, "该数据已存在，请在结果中修改！");
					}else{
						
						boolean flag = manager.createOrUpdateIndex(doc, contentid);
						if(flag){
							resultJson = CommonUtil.returnAjaxJson(flag, "保存成功！");
						}else{
							resultJson = CommonUtil.returnAjaxJson(flag, "保存失败！");
						}
					}
				} catch (Exception e) {
					resultJson = CommonUtil.returnAjaxJson(false, "保存失败！");
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}else{
			resultJson = CommonUtil.returnAjaxJson(false, "必须包含contentid字段！");
		}
		return resultJson;
	}
	
	/**
	 * 通过contentid 查出相应数据
	 * @param indexPath
	 * @param contentid
	 * @return
	 */
	public String getDataById(String indexPath,String contentid){
		String jsonResult = "";
		
		try {
			LuceneManager manager = new LuceneManager(indexPath);
			
			List<LuceneField> fieldList = manager.getDataById(contentid);
			
			Map<String, List<LuceneField>> fieldMap = new HashMap<String, List<LuceneField>>();
			
			fieldMap.put("rows", fieldList);
			
			jsonResult = JSON.toJSONString(fieldMap);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return jsonResult;
	}
	
	/**
	 * 修改数据
	 * @param indexPath
	 * @param docFieldList
	 * @return
	 */
	public String updateOneDocument(String indexPath,List<LuceneField> docFieldList){
		String resultJson = "";
		Map<String, LuceneField> fieldMap = new HashMap<String, LuceneField>();
		for(LuceneField luceneField : docFieldList){
			fieldMap.put(luceneField.getFieldName(), luceneField);
		}
		
		if(fieldMap.containsKey("contentid")){
			
			Document doc = LuceneField.createDocument(fieldMap);
			
			if(doc == null){
				resultJson = CommonUtil.returnAjaxJson(false, "数据有误！");
				return resultJson;
			}else{
				//先查找是否包含contentid
				String contentid = fieldMap.get("contentid").getFieldValue();
				
				try {
					LuceneManager manager = new LuceneManager(indexPath);
					
					boolean flag = manager.createOrUpdateIndex(doc, contentid);
					if(flag){
						resultJson = CommonUtil.returnAjaxJson(flag, "保存成功！");
					}else{
						resultJson = CommonUtil.returnAjaxJson(flag, "保存失败！");
					}
				} catch (Exception e) {
					resultJson = CommonUtil.returnAjaxJson(false, "保存失败！");
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}else{
			resultJson = CommonUtil.returnAjaxJson(false, "必须包含contentid字段！");
		}
		return resultJson;
	}
	
}
